package org.abratuhi.kvngroupware.registration.mptua;

import java.util.List;

import org.abratuhi.kvngroupware.network.Client;
import org.abratuhi.kvngroupware.network.Message;
import org.abratuhi.kvngroupware.network.MessageProceeder;
import org.abratuhi.kvngroupware.registration.manager.RegistrationManager;
import org.abratuhi.kvngroupware.team.model.Team;
import org.abratuhi.kvngroupware.widget.WidgetManager;
import org.jdom.Element;

public class RegistrationResponseMessageProceeder implements MessageProceeder{
	RegistrationManager regmanager;
	WidgetManager widgetmanager;
	
	public RegistrationResponseMessageProceeder(RegistrationManager regmanager, WidgetManager widgetmanager){
		this.regmanager = regmanager;
		this.widgetmanager = widgetmanager;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void proceedMessage(Client client, Message message) {
		Element response = message.getRoot().getChild("response");
		String type = response.getAttributeValue("type");
		String action = response.getAttributeValue("action");
		String status = response.getAttributeValue("status");
		
		if(type.equals("user")){
			
		}
		else if(type.equals("team")){
			Team t = Team.fromElement(response.getChild("team"));
			
			if(status.equals("ok")){
				if(action.equals("create")){
					regmanager.put(t.getId(), t);
				}
				else if(action.equals("get")){
					List<Element> teams = response.getChildren("team");
					for(int i=0; i<teams.size(); i++){
						Team team = Team.fromElement(teams.get(i));
						regmanager.put(team.getId(), team);
					}
				}
				else if(action.equals("update")){
					regmanager.update(t.getId(), t);
				}
				else if(action.equals("delete")){
					regmanager.remove(t.getId());
				}
			}
			
			if(widgetmanager.contains("register"))
				widgetmanager.get("register").repaint();
		}
	}

}
